package com.mapapp.flutter_mapapp.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.ScrollView;
import android.widget.TextView;

import com.mapapp.flutter_mapapp.R;
import com.mapapp.flutter_mapapp.adapter.StepAdapter;
import com.mapapp.flutter_mapapp.bean.DetailTree;
import com.mapapp.flutter_mapapp.persenter.RegionSelectionPresenter;
import com.mapapp.flutter_mapapp.util.ScreenUtil;
import com.mapapp.flutter_mapapp.util.ToastUtils;
import com.mapapp.flutter_mapapp.view.RegionSelectionViewInterface;
import com.mapapp.flutter_mapapp.widget.SurveyOptionsDialog;
import com.mapapp.flutter_mapapp.widget.TitleBar;
import com.unnamed.b.atv.model.TreeNode;
import com.unnamed.b.atv.view.AndroidTreeView;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class RegionSelectionActivity extends ImmersiveBaseActivity implements RegionSelectionViewInterface {

    @BindView(R.id.tree_container)
    ScrollView treeContainer;
    @BindView(R.id.rv_step)
    RecyclerView rvStep;
    @BindView(R.id.title_bar)
    TitleBar titleBar;

    private TreeNode root;
    private AndroidTreeView tView;
    private String taskId;
    private SurveyOptionsDialog surveyOptionsDialog;


    private TreeNode currentNode;
    private TreeNode preNode;

    private RegionSelectionPresenter presenter;

    private StepAdapter stepAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_region_selection);
        ButterKnife.bind(this);

        taskId = getIntent().getStringExtra("task_id");
        presenter = new RegionSelectionPresenter(this, this, lifecycleSubject);
        root = TreeNode.root();

        tView = new AndroidTreeView(this, root);
        treeContainer.setMinimumWidth(ScreenUtil.getScreenWidth(mContext));
        treeContainer.addView(tView.getView());
        tView.setDefaultAnimation(false);
        tView.setDefaultContainerStyle(R.style.TreeNodeStyleCustom);
        tView.setUseAutoToggle(false);
        tView.setDefaultNodeClickListener(new TreeNode.TreeNodeClickListener() {
            @Override
            public void onClick(final TreeNode node, final Object value) {
                currentNode = node;
                preNode = node;
                final DetailTree tree = (DetailTree) value;
                titleBar.getTitleBarCenter().setText(tree.getRegionName());
                if (!tree.isLeaf() && node.getChildren().size() == 0) {
                    presenter.getTreeList(taskId, tree.getRegionId());
                } else {
                    stepAdapter.setNewData(tree.getProcesses());
                    if (tree.isLeaf()) {
                        if (tree.getFixNoAuditNum() > 0) {
                            ToastUtils.showMessage(mContext, "当前有未审核数据，请等待审核");
                            return;
                        }

                        if (surveyOptionsDialog == null) {
                            surveyOptionsDialog = new SurveyOptionsDialog(mContext);
                        }
                        surveyOptionsDialog.showPopupWindow();
                        surveyOptionsDialog.setListener(new SurveyOptionsDialog.OnItemClickListener() {
                            @Override
                            public void onClick(int type) {
                                if ((type == 1 || type == 2) && TextUtils.isEmpty(tree.getProcessNow())) {
                                    ToastUtils.showMessage(mContext, "没有已完成的步骤，无法修改覆盖");
                                    return;
                                }
                                String regionId = tree.getRegionId();
                                Intent intent = new Intent(mContext, NewDataActivity.class);
                                intent.putExtra("regionId", regionId);
                                intent.putExtra("type", type);
                                intent.putExtra("address", tree.getAddress());
                                startActivity(intent);
                            }
                        });
                    } else {
                        tView.toggleNode(currentNode);
                        ImageView icon = currentNode.getViewHolder().getView().findViewById(R.id.expand);
                        icon.setSelected(currentNode.isExpanded());
                    }
                }
            }
        });


        stepAdapter = new StepAdapter(R.layout.item_step, null);
        rvStep.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        rvStep.setAdapter(stepAdapter);

        titleBar.getIvBack().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });

        presenter.getTreeList(taskId, "-1");
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (currentNode != null) {
            DetailTree value = (DetailTree) currentNode.getValue();
            if (value.isLeaf()) {
                presenter.updateNode(taskId, value.getParentId());
            }
        }
    }

    @Override
    public void showTreeList(List<DetailTree> detailTreeList) {
        if (detailTreeList != null && !detailTreeList.isEmpty()) {
            if (detailTreeList.get(0).getIsRoot() == 1) {
                for (DetailTree detailTree : detailTreeList) {
                    TreeNode treeNode = new TreeNode(detailTree).setViewHolder(new MyHolder(mContext));
                    root.addChild(treeNode);
                }
                tView.expandNode(root);
                stepAdapter.setNewData(detailTreeList.get(0).getProcesses());
                titleBar.getTitleBarCenter().setText(detailTreeList.get(0).getRegionName());
            } else {
                for (DetailTree detailTree : detailTreeList) {
                    TreeNode treeNode = new TreeNode(detailTree).setViewHolder(new MyHolder(mContext));
                    treeNode.setSelected(false);
                    currentNode.addChild(treeNode);
                }
                tView.expandNode(currentNode);
                ImageView icon = currentNode.getViewHolder().getView().findViewById(R.id.expand);
                icon.setSelected(true);

                DetailTree nodeValue = (DetailTree) currentNode.getValue();
                stepAdapter.setNewData(nodeValue.getProcesses());
            }
        }
    }

    //更新单个node
    @Override
    public void showUpdateNode(List<DetailTree> detailTreeList) {
        if (detailTreeList != null && !detailTreeList.isEmpty()) {
            //移除子节点
            TreeNode parent = currentNode.getParent();
            if (parent == null) {
                return;
            }
            List<TreeNode> children = parent.getChildren();
            for (int i = children.size() - 1; i >= 0; i--) {
                parent.deleteChild(children.get(i));
            }
            //使当前节点为父节点
            currentNode = parent;
            //添加新的子节点
            for (DetailTree detailTree : detailTreeList) {
                TreeNode treeNode = new TreeNode(detailTree).setViewHolder(new MyHolder(mContext));
                treeNode.setSelected(false);
                currentNode.addChild(treeNode);
                if (preNode != null) {
                    DetailTree preNodeValue = (DetailTree) preNode.getValue();
                    if (preNodeValue != null && preNodeValue.getId() != null && preNodeValue.getId().equals(detailTree.getId())) {
                        preNode = treeNode;
                    }
                }
            }
            tView.expandNode(currentNode);
            ImageView icon = currentNode.getViewHolder().getView().findViewById(R.id.expand);
            icon.setSelected(true);

            DetailTree nodeValue = (DetailTree) preNode.getValue();
            stepAdapter.setNewData(nodeValue.getProcesses());

        }
    }

    public class MyHolder extends TreeNode.BaseNodeViewHolder<DetailTree> {

        MyHolder(Context context) {
            super(context);
        }

        @Override
        public View createNodeView(TreeNode node, DetailTree value) {
            final LayoutInflater inflater = LayoutInflater.from(context);
            final View view = inflater.inflate(R.layout.item_parent_node, null, false);
            TextView tvValue = view.findViewById(R.id.tv_title);
            tvValue.setText(value.getRegionName());

            ImageView expand = view.findViewById(R.id.expand);
            if (value.isLeaf()) {
                expand.setVisibility(View.INVISIBLE);
            } else {
                expand.setVisibility(View.VISIBLE);
            }

            return view;
        }

    }
}
